#!/usr/bin/env python
# -*- coding: utf-8 -*-

""" By Martin Senande-Rivera
    For Towards and atmosphere more favourable to firestorm development in Europe """

import os
import glob, sys
import numpy as np
import xarray as xr
import pandas as pd

GCM=sys.argv[1]  # Enter GCM
RCM=sys.argv[2]  # Enter RCM
rcp=sys.argv[3]  # Enter RCP scenario

path_ki='../0-DATA/FWI/'+RCM+'/'+GCM+'/FWI/'
path_ki='../0-DATA/K-index/'+RCM+'/'+GCM+'/'
path_outs='./'+RCM+'/'+GCM+'/'
path_thres='../1-FWI/'+RCM+'/'+GCM+'/'

from dask_mpi import initialize
initialize()

from distributed import Client
client = Client()

# Read files
fwis=sorted(glob.glob(path_fwi+'fwi_historical_*.nc')+glob.glob(path_fwi+'fwi_'+rcp+'_*.nc'))
FWI = xr.open_mfdataset(fwis,combine='by_coords')['fwi']
FWI= FWI.sel(time=slice('1970-01-01','2098-12-31'))

# Read files
kindexs=sorted(glob.glob(path_kindex+'Ki_historical_*.nc')+glob.glob(path_kindex+'Ki_'+rcp+'_*.nc'))
Ki = xr.open_mfdataset(kindexs,combine='by_coords')['Ki']
Ki = Ki.sel(time=slice('1970-01-01','2098-12-31'))

FWI_thres = xr.open_dataset(path_thres+'FWI_90threshold_'+rcp+'.nc')['fwi'] # FWI threshold
Ki_thres = xr.full_like(FWI_thres,25.)                                      # Kindex threshold 

Ki['time']=FWI['time'] # Skip possible differences in time dimension deffinition

num = xr.full_like(Ki, 0)                               # Daily array full of 0
num = xr.where((FWI>FWI_thres) & (Ki>Ki_thres),1,num)   # Days with FWI and Ki above each threshold are classified as 1
ndays = num.chunk({'time':-1,'rlat': 15, 'rlon': 15}).resample(time='1Y').sum(dim='time')       # Number of days with FWI and Ki above each threshold
ndays.chunk({'time':-1,'rlat': 15, 'rlon': 15}).to_netcdf(path_outs+'FWI-Ki_ndays_'+rcp+'.nc')  # Save output
